package com.example.demo.untils;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

public class RecordingMp4Utils {
    private static String ffmpegPath = "D:\\jdk18\\ffmpeg-4.3.1-full_build\\bin\\ffmpeg";
    private static final String PLAYLIST = "stream.m3u8";
    private static final String FINAL_OUTPUT1 = "final_output.mp4";


    public static void  mergeTsToMp4(String inputDir, String outputFile) throws IOException {
        List<String> tsFiles = Files.walk(Paths.get(inputDir))
                .filter(p -> p.toString().endsWith(".ts"))
                .sorted()
                .map(Path::toString)
                .collect(Collectors.toList());

        if (tsFiles.isEmpty()) {
            throw new IllegalArgumentException("No TS files found in: " + inputDir);
        }

        String cmd = String.format(ffmpegPath+" -i \"concat:" + String.join("|", tsFiles) + "\" -c copy " + outputFile);
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd);

            // 读取输出流避免缓冲区阻塞（重要！）
            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                while (reader.readLine() != null) {
                } // 消费输出
            }
            int exitCode = process.waitFor();
            if (exitCode != 0) {
                throw new IOException("FFmpeg failed, exit code: " + exitCode);
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw new IOException("Process interrupted", e);
        } finally {
            if (process != null) {
                process.destroy(); // 强制终止
                if (process.isAlive()) {
                    process.destroyForcibly(); // 如果普通终止失败
                }
            }
        }
    }

    public static void fastMergeTs(String inputDir, String output) throws IOException, InterruptedException {
        // 1. 生成文件列表
         List<Path>  tsFiles= Files.walk(Paths.get(inputDir))
                .filter(Files::isRegularFile)
                .sorted()
                .collect(Collectors.toList());


        Path listFile = Files.createTempFile("ffmpeg-list", ".txt");
        Files.write(listFile,
                tsFiles.stream()
                        .map(p -> "file '" + p.toAbsolutePath() + "'")
                        .collect(Collectors.toList())
        );

        // 2. 构建高效命令
        String cmd = String.format(
                "ffmpeg -f concat -safe 0 -i \"%s\" -c copy -map_metadata -1 -fflags +genpts \"%s\"",
                listFile,
                output
        );

        // 3. 使用ProcessBuilder
        ProcessBuilder pb = new ProcessBuilder(cmd.split(" "));
        pb.redirectErrorStream(true);

        Process process = pb.start();
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {

            // 4. 带超时控制
            if (!process.waitFor(30, TimeUnit.MINUTES)) {
                process.destroyForcibly();
                throw new IOException("Process timeout");
            }

            if (process.exitValue() != 0) {
                throw new IOException("Merge failed");
            }
        } finally {
          //  Files.deleteIfExists(listFile);
            if (process != null) {
                process.destroy(); // 强制终止
                if (process.isAlive()) {
                    process.destroyForcibly(); // 如果普通终止失败
                }
            }
        }
    }


    private static void convertHlsToMp4() throws IOException, InterruptedException {
        ProcessBuilder pb = new ProcessBuilder(
                ffmpegPath,
                "-i",  "D:\\jdk18\\hls2\\"+ PLAYLIST,
                "-c", "copy",
                "D:\\jdk18\\hls2\\" +FINAL_OUTPUT1
        );

        Process process = pb.start();
        int exitCode = process.waitFor();
        System.out.println("转换完成，退出码: " + exitCode);
    }

    private static void recordToMp4Byurl() throws IOException, InterruptedException {
        String[] cmd = {
                ffmpegPath,
                "-i", "rtsp://127.0.0.1:554/easy1.mp4",
                "-c:v", "copy",
                "-c:a", "copy",
                "-f", "mp4",
                "D:\\jdk18\\hls2\\" +FINAL_OUTPUT1
        };
        ProcessBuilder pb = new ProcessBuilder(cmd);
        Process process = pb.start();
        int exitCode = process.waitFor();
        System.out.println("转换完成，退出码: " + exitCode);
    }


    /**
     * 合并TS分片到单个文件
     * @param inputDir 分片所在目录
     * @param outputFile 输出文件路径
     * @throws IOException 文件操作异常
     * @throws InterruptedException 进程中断异常
     */
    public static boolean mergeTSFiles(String inputDir, String outputFile)
            throws IOException, InterruptedException {

        // 1. 获取并排序TS文件
        File dir = new File(inputDir);
        File[] tsFiles = dir.listFiles((d, name) -> name.endsWith(".ts"));
        if (tsFiles != null) {
            Arrays.sort(tsFiles, (f1, f2) -> {
                long num1 =   Long.valueOf (f1.getName().replace(".ts", ""));
                long num2 =Long.valueOf(f2.getName().replace(".ts", ""));
                return Long.compare(num1, num2);
            });
        }

        if (tsFiles == null || tsFiles.length == 0) {
            throw new FileNotFoundException("未找到TS分片文件");
            //return  false;
        }
        Path path = Path.of(outputFile);
        if (Files.exists(path)) {
            Files.delete(path);
        }
        ///////////////////
        List<File> sortedFiles = new ArrayList<>(List.of(tsFiles));
        sortedFiles.sort(Comparator.comparing(File::getName));
        // 2. 创建临时文件列表
        File listFile = new File(inputDir, "file_list.txt");
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(listFile))) {
            for (File file : sortedFiles) {
                writer.write("file '" + file.getAbsolutePath() + "'\n");
            }
        }
        // 3. 执行FFmpeg合并命令
        ProcessBuilder pb = new ProcessBuilder(
                ffmpegPath,
                "-f", "concat",
                "-safe", "0",
                "-i", listFile.getAbsolutePath(),
                "-c", "copy",
                outputFile
        );

        pb.redirectErrorStream(true);
        Process process = pb.start();

        // 读取FFmpeg输出日志
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(process.getInputStream()))) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println("[FFmpeg] " + line);
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("FFmpeg合并失败，退出码: " + exitCode);
        }
        process.destroy();
        // 4. 清理临时文件
        listFile.delete();
        return true;
    }


}
